package comag

import (
	"context"
	"sync"
)

// FailAllFailCoMag 一次失败全部失败的CoMag
// 已废弃，请使用 ConProcessModelActuator 进行处理
type FailAllFailCoMag struct {
	coArr []CoFunc
	wg    sync.WaitGroup
}

func NewFailAllFailCoMag() *FailAllFailCoMag {
	return &FailAllFailCoMag{
		coArr: []CoFunc{},
	}
}

func (mg *FailAllFailCoMag) Add(f CoFunc) {
	mg.coArr = append(mg.coArr, f)
}

func (mg *FailAllFailCoMag) Run() {
	ctx, cancel := context.WithCancel(context.Background())
	errCh := make(chan error)
	ctx = context.WithValue(ctx, "error", errCh)
	for _, f := range mg.coArr {
		do := f
		mg.wg.Add(1)
		go func() {
			do(ctx)
			mg.wg.Done()
		}()
	}

	//监听 err ch
	go func() {
		for {
			select {
			case err := <-errCh:
				debugPrint("happen err: %s", err.Error())
				cancel()
			}
		}
	}()

	mg.wg.Wait()
}
